﻿using System;
using System.Web;
using System.Web.Caching;
using XRM.Security.DataAccess;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.DataAccess.Repositories.Impl;

namespace XRM.Security.WebUI.Security
{
    public interface ICurrentUserService
    {
        UserPrincipal GetPrincipal( HttpContextBase httpContext );
        void DeletePrincipal( HttpContextBase httpContext );
    }

    public class CurrentUserService : ICurrentUserService
    {
        /// <summary>
        /// Предоставляет сведения об авторизованном пользователе на основе http контекста.
        /// </summary>
        public UserPrincipal GetPrincipal( HttpContextBase httpContext )
        {
            if ( !httpContext.User.Identity.IsAuthenticated )
            {
                return null;
            }
            var userName = httpContext.User.Identity.Name;
            var principal = (UserPrincipal)httpContext.Cache.Get( userName );
            if ( principal == null )
            {
                using ( var dataManager = new DataManager())
                {
                    var user = dataManager.SystemUserRepository.GetByLogin( userName );
                    if ( user == null )
                    {
                        return null;
                    }
                    principal = new UserPrincipal
                    {
                        DisplayName = user.FullName(),
                        Name = userName,
                        UserId = user.Id,
                        IsAuthenticated = true
                    };
                    httpContext.Cache.Add( userName, principal, null, Cache.NoAbsoluteExpiration, new TimeSpan( 0, 30, 0 ), CacheItemPriority.Default, null );
                }
            }
            return principal;
        }

        /// <summary>
        /// Удаление сведений об авторизованном пользователе из кэша.
        /// </summary>
        public void DeletePrincipal( HttpContextBase httpContext )
        {
            if ( httpContext.User.Identity.IsAuthenticated )
            {
                httpContext.Cache.Remove( httpContext.User.Identity.Name );
            }
            httpContext.User = null;
        }
    }
}